<template>
  <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect">
    <el-menu-item index="home">首页</el-menu-item>
    <el-menu-item index="recommend">推荐</el-menu-item>
    <el-sub-menu v-for="(item, index) in mainMenuItems" :key="item.id" :index="item.id.toString()">
      <template #title>{{ item.name }}</template>
      <el-menu-item v-for="(subItem, subIndex) in item.children" :key="subItem.id" :index="`${item.id}-${subItem.id}`">
        {{ subItem.name }}
      </el-menu-item>
      <!-- If the main menu item is 专业 and user is admin -->
      <el-menu-item v-if="item.id === proMenuId && isAdmin" :key="`${item.id}-add`" :index="`${item.id}-add`">
        添加专业
      </el-menu-item>
    </el-sub-menu>
    <el-menu-item index="search">搜索</el-menu-item>
    <div :style="{ width: spacerWidth + 'px' }"></div>
    <el-menu-item index="publish">发帖</el-menu-item>
    <el-menu-item index="profile">个人</el-menu-item>
  </el-menu>

  <el-dialog title="添加专业" v-model="dialogVisible">
    <el-input v-model="newCategoryName" placeholder="请输入专业名称"></el-input>
    <el-divider></el-divider>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="addCategory">确认</el-button>
    </span>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import axiosInstance from '../plugins/axios'

const router = useRouter()
const store = useStore()
const mainMenuItems = ref([])

const spacerWidth = ref(0)

const calculateSpacerWidth = () => {
  spacerWidth.value = window.innerWidth - 90 * 6
}

const processMenuItems = (items) => {
  const menuMap = new Map()

  items.forEach(item => {
    if (!item.id) {
      console.error('Item missing id:', item)
      return
    }

    if (item.parentId === null) {
      menuMap.set(item.id, { ...item, children: [] })
    } else {
      if (!menuMap.has(item.parentId)) {
        menuMap.set(item.parentId, { id: item.parentId, name: '', children: [] })
      }
      menuMap.get(item.parentId).children.push(item)
    }
  })

  return Array.from(menuMap.values())
}

const fetchMenuItems = async () => {
  try {
    const response = await axiosInstance.get('/categories')
    const items = response.data

    // Find the ID of the 专业 menu item
    const proItem = items.find(item => item.name === '专业')
    if (proItem) {
      proMenuId.value = proItem.id
    }

    mainMenuItems.value = processMenuItems(items)
    await nextTick() // 确保菜单项渲染完成后再计算宽度
    calculateSpacerWidth()
  } catch (error) {
    console.error('Error fetching menu items:', error)
  }
}

onMounted(() => {
  fetchMenuItems()
  window.addEventListener('resize', calculateSpacerWidth)
})

onUnmounted(() => {
  window.removeEventListener('resize', calculateSpacerWidth)
})

const activeIndex = ref('home')
const handleSelect = (key: string, keyPath: string[]) => {
  if (key === 'home') {
    router.push('/home')
  } else if (key.startsWith('recommend')) {
    router.push('/recommend')
  } else if (key.startsWith('search')) {
    router.push('/search')
  } else if (key.startsWith('publish')) {
    router.push('/publish')
  } else if (key.startsWith('profile')) {
    router.push('/profile')
  } else if (key.endsWith('add')) {
    dialogVisible.value = true
    currentParentId.value = parseInt(key.split('-')[0])
  } else {
    const [parentId, childId] = key.split('-')
    router.push({ name: 'category', params: { categoryId: childId } })
  }
}

const dialogVisible = ref(false)
const newCategoryName = ref('')
const currentParentId = ref<number | null>(null)
const proMenuId = ref<number | null>(null) // 动态确定专业菜单项的id

const addCategory = async () => {
  if (!newCategoryName.value) {
    return
  }

  try {
    await axiosInstance.post(`/categories?name=${newCategoryName.value}&parentId=${currentParentId.value}`)
    dialogVisible.value = false
    newCategoryName.value = ''
    fetchMenuItems() // 重新获取菜单项
  } catch (error) {
    dialogVisible.value = false
    console.error('Error adding category:', error)
  }
}

// 判断用户是否为管理员
const isAdmin = computed(() => store.getters.isUserAdmin)
</script>